package com.zazbug.blog.entity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Set;

public class ClearImgUtils {

	private RedisTemplate redisTemplate;

	@Value(value = "uploadImgFile")
	private String uploadImgFile;

	@Value(value = "submitImgFile")
	private String submitImgFile;

	@Value("${web.upload-path}")
	private String imgPath;

	public ClearImgUtils(){
		redisTemplate = new RedisTemplate();
	}

	// 将上传的图片添加到集合
	public void pushUploadImgList(String fileName){
		String path = getPath(fileName);
		redisTemplate.opsForSet().add("uploadImgFile",path);
	}

	// 将提交的图片添加到集合
	public void pushSubmitImgList(String fileName){
		String path = getPath(fileName);
		redisTemplate.opsForSet().add("submitImgFile",path);
	}

	// 删除多余图片
	public void rmUnnImg(){
		Set<String> set = redisTemplate.opsForSet().difference(uploadImgFile, submitImgFile);
		if(set != null){
			for (String fileName : set) {
				String path = imgPath + fileName;
				File file = new File(path);
				// 文件是否存在
				if(file.exists()){
					file.delete();
				}
			}
		}

	}

	// 截取路径
	private String getPath(String fileName){
		int lastIndexOf = fileName.lastIndexOf("image/");
		String path = fileName.substring(lastIndexOf + 6, fileName.length());
		return path;
	}
}
